package light.head.dao.el;

import java.util.List;

import org.springframework.stereotype.Service;

import light.head.dto.ExamTopic;
import light.head.enm.RESULT;
import light.head.framework.base.BaseDAO;
import light.head.model.el.TopicAnswer;
@Service
public class TopicAnswerDAO extends BaseDAO<TopicAnswer, Integer>{
	private final String hql_findKeyByCode = "FROM TopicAnswer tk WHERE tk.deleted = 0 AND tk.tc = ? ";
	/**
	 * 通过题目code找到相关答案
	 * @param code
	 * @return
	 */
	public List<TopicAnswer> findKeyByCode(Integer code){
		if(code != null){
			return find(hql_findKeyByCode,code);
		}
		return null;
	}
	
	
	/**
	 * 修改验证
	 */
	public RESULT update(TopicAnswer tk){
		if(tk == null || tk.getCode() == null) return RESULT.ERROR;
		
		TopicAnswer old = get(tk.getCode());
		
		if(old == null){
			return RESULT.NOT_FIND;
		}
		
		if(isNotNull(tk.getAnswer()) && !tk.equals(old.getAnswer())){
			old.setAnswer(tk.getAnswer());
		}
		if(tk.getIsRight() == null){
			old.setIsRight(false);
		}else{
			old.setIsRight(true);
		}
		
		if(tk.getOc() != null && tk.getOc() != old.getOc()){
			old.setOc(tk.getOc());
		}
		if(tk.getTc() != null && tk.getTc() != old.getTc()){
			old.setTc(tk.getTc());
		}
		if(tk.getDeleted() != null && tk.getDeleted() != old.getDeleted()){
			old.setDeleted(tk.getDeleted());
		}
		return upd(old);
	}
	
	/**
	 * 填充答案到题目
	 * @param list
	 */
	public void addTopicKey(List<ExamTopic> list){
		if(list != null && list.size() > 0){
			for(ExamTopic et : list){
				et.setTkList(findKeyByCode(et.getCode()));
			}
		}
	}
	
	/**
	 * 根据题目编号查找该题正确答案
	 * tc 题目编号
	 */
	public List<TopicAnswer> findKeyisRight(Integer tc){
		String sql = "FROM TopicAnswer tk WHERE tk.deleted = 0 AND tk.isRight = 1 AND tk.tc = ?";
		return find(sql, tc);
	}
}
